package net.zoneland.knowledge.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import net.zoneland.knowledge.enums.QueStyleEnum;
import net.zoneland.knowledge.enums.VisitTypeEnum;
import net.zoneland.knowledge.model.LoginUserPojo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;

import net.zoneland.knowledge.controller.bean.FootPrint;
import net.zoneland.knowledge.dao.QaRecordsV2Mapper;
import net.zoneland.knowledge.model.DataCategory;
import net.zoneland.knowledge.model.QaRecordsV2;
import net.zoneland.knowledge.model.QaRecordsV2Example;
import net.zoneland.knowledge.service.ApiService;
import net.zoneland.knowledge.service.FootprintService;

/**
 * 足迹接口.
 */
@Service
public class FootprintServiceImpl implements FootprintService {

    @Autowired
    private QaRecordsV2Mapper qaRecordsV2Mapper;
    
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
    private static final DateTimeFormatter formatter2= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final ZoneId zoneId = ZoneId.systemDefault();

    @Autowired
    private ApiService apiService;
    
    @Override
    public List<FootPrint> getFootprint(String userId, String time) {
        Date date = null;
        if (StringUtils.isNotBlank(time)){
            date = Date.from(LocalDateTime.parse(time, formatter2).toInstant(ZoneOffset.of("+8")));
        } else {
            date = new Date();
        }
        PageHelper.startPage(1, 10);
        final QaRecordsV2Example example = new QaRecordsV2Example();
        example.createCriteria().andReqIdEqualTo(userId).andCreateTimeLessThan(date);
        example.setOrderByClause(" createtime desc");
        final List<QaRecordsV2> list = qaRecordsV2Mapper.selectByExample(example);
        List<FootPrint> collect = list.stream().map(this::changeFootPrint).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void saveFootprint(final LoginUserPojo loginUserPojo, final FootPrint footPrint) {
        final QaRecordsV2 qaRecordsV2 = new QaRecordsV2(loginUserPojo);
        qaRecordsV2.setId(UUID.randomUUID().toString());
        qaRecordsV2.setQueStyle(QueStyleEnum.PROFESSION_TALK.getValue());
        qaRecordsV2.setQueryText(footPrint.getQueryText());
        qaRecordsV2.setAnsCode(1);
        qaRecordsV2.setFinalAnswer(1);
        final String ansContent = footPrint.getAnsContent();
        qaRecordsV2.setAnsContent(ansContent);
        if (StringUtils.isNotBlank(ansContent) && ansContent.contains("十分抱歉")){
            qaRecordsV2.setHasAnswer(false);
        }
        qaRecordsV2.setCategory(footPrint.getCategory());
        qaRecordsV2.setClickSearch(footPrint.getClickSearch());
        qaRecordsV2.setCreateTime(new Date());
        qaRecordsV2.setVisitType(VisitTypeEnum.getByValue(footPrint.getVisitType()));
        qaRecordsV2Mapper.insert(qaRecordsV2);
    }

    /**
     * 将查询结果转成前端需要的足迹对象.
     * @param qaRecordsV2
     * @return
     */
    private FootPrint changeFootPrint(QaRecordsV2 qaRecordsV2){
        FootPrint footPrint = new FootPrint();
        String[] split = qaRecordsV2.getCategory().split(",");
        StringBuilder category = new StringBuilder();
        final Map<String, DataCategory> dataCategoryMap = apiService.getDataCategory()
            .stream()
            .collect(Collectors.toMap(DataCategory::getKey, d -> d));
        for(String s:split) {
            if (StringUtils.isNotBlank(s)){
                DataCategory dataCategory = dataCategoryMap.get(s);
                if (dataCategory != null) {
                    category.append(dataCategory.getLabel());
                }else {
                    category.append(s);
                }
                category.append("，");
            }
        }
        footPrint.setCategory(category.substring(0,category.length()-1));
        String level1Title = qaRecordsV2.getLevel1Title();
        if (StringUtils.isBlank(level1Title)){
            level1Title = "--";
        }
        footPrint.setLevel1Title(level1Title);
        Date createTime = qaRecordsV2.getCreateTime();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(createTime.toInstant(), zoneId);
        String time = localDateTime.format(formatter);
        if (time.equals(LocalDate.now().format(formatter))){
            time += "（今天）";
        }
        footPrint.setCreateTime(createTime);
        footPrint.setTime(time);
        String queryText = qaRecordsV2.getQueryText();
        if (StringUtils.isBlank(queryText)) {
            queryText = "--";
        }
        footPrint.setQueryText(queryText);
        footPrint.setVisitType(qaRecordsV2.getVisitType().toString());
        return footPrint;
    }
}
